package com.apexsoft.front.common.servlet;

import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.apexsoft.front.common.filter.FilterManager;
import com.apexsoft.front.common.plugins.filter.IFilter;
import com.apexsoft.front.common.plugins.filter.annotation.AFilter;
import com.apexsoft.front.common.plugins.loader.ILoader;
import com.apexsoft.front.common.plugins.loader.annotation.ALoader;
import com.apexsoft.front.common.utils.ClassesUtil;

/**
 * Common init servlet
 * @author dinglei
 *
 */
public class StartServlet extends HttpServlet {
	
	private static final Logger log  = LogManager.getRootLogger();

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public void init() throws ServletException
	{
		ServletContext sc = this.getServletContext();
		
		this.loadLoaderByAnnotation(sc);
		this.loadFilterByAnnotation();

		//设置JVM参数
		System.setProperty("java.net.preferIPv4Stack", "true");
	}
	
	/**
	 * 根据注解加载"加载器插件"
	 * @param sc
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	private void loadLoaderByAnnotation(ServletContext sc){
		Set<Class<?>> cls = ClassesUtil.getClassesByAnnotation("com.apexsoft",ALoader.class);
	    Object[] arr = cls.toArray();
	    for(int i=0;i<arr.length;i++){
	    	Class<?> c = (Class<?>)arr[i];
	    	if(c.getName().startsWith("com.apexsoft.front.common.plugins.loader.impl")){
		    	try{
			    	ILoader loader = (ILoader)c.newInstance();
		    		loader.load(sc);
		    		log.info("[Loader] load plugin success: "+c.getName());
		    	}catch(Exception e){
		    		log.error(e.getMessage());
		    		e.printStackTrace();
		    	}
	    	}
	    }
	    for(int i=0;i<arr.length;i++){
	    	Class<?> c = (Class<?>)arr[i];
	    	if(!c.getName().startsWith("com.apexsoft.front.common.plugins.loader.impl")){
		    	try{
			    	ILoader loader = (ILoader)c.newInstance();
		    		loader.load(sc);
		    		log.info("[Loader] load plugin success: "+c.getName());
		    	}catch(Exception e){
		    		log.error(e.getMessage());
		    		e.printStackTrace();
		    	}
	    	}
	    }
	}
	
	/**
	 * 加载初始化过滤器对象
	 */
	private void loadFilterByAnnotation(){
		Set<Class<?>> cls = ClassesUtil.getClassesByAnnotation("com.apexsoft",AFilter.class);
	    Object[] arr = cls.toArray();
	    for(int i=0;i<arr.length;i++){
	    	Class<?> c = (Class<?>)arr[i];
	    	try{
	    		IFilter filter = (IFilter)c.newInstance();
        		FilterManager.addFilter(filter);
        		log.info("[Filter] load plugin success: "+c.getName());
	    	}catch(Exception e){
	    		log.error(e.getMessage());
	    		e.printStackTrace();
	    	}
	    }
	}

}
